package com.crowdgeeks.common.util;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

public final class WebUrlUtils {

	/**
	 * 요청된 Url을 구합니다.(포트, 컨텍스트 포함)
	 * @param request Request 객체
	 * @param includeQuerystring Querystring 포함 여부
	 * @return
	 */
	public static String getRequestUrl(HttpServletRequest request, boolean includeQuerystring) {		
		StringBuffer returnValueBuffer = new StringBuffer();
		String path = request.getContextPath();

		returnValueBuffer.append(request.getScheme()).append("://").append(request.getServerName());
		if ( request.getServerPort() != 80 ) {
			returnValueBuffer.append(request.getServerPort());		    
		}
		if ( !path.equals("") ) {			
			returnValueBuffer.append(path);
		}
		
		returnValueBuffer.append(request.getServletPath());

		if(includeQuerystring) {
			String query = request.getQueryString();

			if (query != null) {				
				returnValueBuffer.append("?").append(query);
			}
		}
		return returnValueBuffer.toString();
	}


	/**
	  * BASE64 Decoder
	  */
	public static String base64Decode(String str) {
		String result = "";
		try {
			sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
			byte[] decodeByte = decoder.decodeBuffer(str);
			result = new String(decodeByte);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return result;
	} 
	
}
